import axios, { AxiosError, AxiosInstance } from "@ohos/axios";
import { HttpRequestConfig } from './HttpRequestConfig';
import { InterceptorHooks } from './InterceptorHooks';
import { promptAction } from '@kit.ArkUI';


/**
 * @ProjectName : MyApplication
 * @FileName : AxiosHttpRequest
 * @Author : 小北哥
 * @Time : 2024/8/1
 *
 *  axios请求与拦截
 */
class BaseAxiosRequest {
  config: HttpRequestConfig;
  interceptorHooks?: InterceptorHooks;
  instance: AxiosInstance;

  constructor(options: HttpRequestConfig) {
    this.config = options;
    this.interceptorHooks = options.interceptorHooks;
    this.instance = axios.create(options);
    this.setupInterceptor();
    //请求拦截
    this.instance.interceptors.request.use((config) => {
        const token =
          'eyJuaWNrbmFtZSI6IiIsImlkIjoiNDE1MTUxMTI0MTkxOTIiLCJ1aWQiOiI0MTUxNTExMjQxOTE5MiIsImV4cCI6IjIwMjQtMTEtMDYgMDk6NTg6MDMiLCJhcHBfaWRlbnRpdHkiOiJ1YyIsInRlbmFudF9pZCI6MSwic2lnbiI6IlNHTjAyZHJVdjZPY3FoUldZYnEzMkJMb3ROaXdNSmkyb2dLYlc3bGY1ekd5OGNPSVlyZy9SajlBWXFVWDY0WTN1MnpXbjBDTzUwdmp5dlV4M3FkQjVGM1RTc1RablBlM0FLTVBBNG4vajVwQ2pzeTIxQUNmTVlQNmtOQW41TW8zQWZXZGo2aXVqbXo2ZmtJemhUN1ZPMTRXVjY5RGFSNTVHVEpONVU5YWkwNGVsSlFnT3pBZ09MQzhjUHNJeUNoNVhkSnZMck51SVlRSGNGdkRZNWZtckV6cmJrZGpiNnA1R2xjdC9rRFAyUGtOTXZSSm9NL1gvTDBiQWdvT1ZWUkZPbHUzQ0krN3drZXRuQmx6QlhqWHBlcHNRdkxMYXFSc043dnV3aDUwNGhQY1ZDYStxbE5NQ2xQMFAwVzY1bFM4bmhSa0NiWG01QWV0UlpRQUJEeW9Vdz09In0_';
        if (token) {
          config.headers.token = token;
        }
        return config;
      }, (err) => {
      }
    );
  }

  setupInterceptor(): void {
    this.instance.interceptors.request.use(
      /**
       * 这里主要是高版本的axios中设置拦截器的时候里面的Config属性必须是InternalAxiosRequestConfig
       * 但是InternalAxiosRequestConfig里面的headers是必传
       * 所以在实现的子类我设置成非必传会报错，加了个忽略注解
       */
      // @ts-ignore
      this.interceptorHooks?.requestInterceptor,
      this.interceptorHooks?.requestInterceptorCatch,);
      this.instance.interceptors.response.use(
      this.interceptorHooks?.responseInterceptor,
      this.interceptorHooks?.responseInterceptorCatch,);
  }

  // 类型参数的作用，T决定AxiosResponse实例中data的类型
  request<T = any>(config: HttpRequestConfig): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      this.instance.request<any, T>(config).then(res => {
        resolve(res);
      }).catch((err) => {
        console.error("网络请求Request异常：" + err.message);
        errorHandler(err);
        if (err) {
          reject(err);
        }
      });
    });
  }

  get<T = any>(config: HttpRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'GET' });
  }

  post<T = any>(config: HttpRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'POST' });
  }

  delete<T = any>(config: HttpRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'DELETE' });
  }

  patch<T = any>(config: HttpRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'PATCH' });
  }
}

export function errorHandler(error: any) {
  if (error instanceof AxiosError) {
    promptAction.showToast({ message: error.message });
  } else if (error != undefined && error.response != undefined && error.response.status) {
    switch (error.response.status) {
      case 401:

        break;
      default:
        promptAction.showToast({ message: error.response.data.message });
    }
  } if (error != undefined && error.data != undefined && error.data.code) {
    switch (error.data.code) {
      case 4000:
      case 4001:  //DOTO 未登录的情况
      case 12004:
      case 12204:
        promptAction.showToast({ message:`${error.data.msg}` })
        break;
      default:
        promptAction.showToast({ message: error.data.msg });
    }
  }
}

export default BaseAxiosRequest;